package com.lam.framework.operLog.handlers;

import java.util.TimerTask;

import javax.servlet.http.HttpServletRequest;

import com.lam.common.context.TokenUtils;
import com.lam.common.utils.BeanUtil;
import com.lam.common.utils.JsonUtil;
import com.lam.common.utils.SpringUtils;
import com.lam.framework.async.AsyncManager;
import com.lam.framework.operLog.enums.BusinessType;
import com.lam.framework.operLog.enums.OperatorType;
import com.lam.framework.operLog.model.OperateLog;
import com.lam.framework.operLog.service.OperLogService;

public class AuthInfoUtil {
	
	public static String getOperName(OperatorType operatorType, BusinessType businessType, Object[] loginInParam) {
		if(businessType == BusinessType.LOGIN_IN) {
			if(operatorType == OperatorType.ADMIN) {
				//LoginBody对象的username
				return JsonUtil.toString(BeanUtil.getValueByName(loginInParam[0], "username"));
			}
			return "appLoginIn";
//				return Base64Util.decode(JsonUtil.toString(BeanUtil.getValueByName(loginInParam[0], "username")));
			//LoginBody对象的username
//			String username = JsonUtil.toString(BeanUtil.getValueByName(loginInParam[0], "username"));
//			return getOperatorType(operatorType) == OperatorType.FRONT? Base64Util.decode(username) : username;
		}
		if(businessType == BusinessType.LOGIN_CAPTCHA_CODE) {
			return (String) loginInParam[0];
		}
		return AuthInfoUtil.getLoginUsername();
	}
	
	public static String getLoginUsername() {
		return TokenUtils.getLoginUsername();
	}
	
	public static OperatorType getOperatorType(OperatorType operatorType) {
		if(operatorType == null || OperatorType.AUTO == operatorType) {
			return OperatorType.valueFrom(TokenUtils.getAuthType().getTokenPrefix());
		}
		return operatorType;
	}
	
	public static HttpServletRequest getRequest(){
		return SpringUtils.getRequest();
	}
	
	public static void saveLog(OperLogService service, OperateLog operLog) {
		//异步保存数据库
		AsyncManager.execute(new TimerTask() {
			@Override
			public void run() {
				service.saveLog(operLog);
			}
		});
	}
	
}
